import { Button, message } from 'antd';
import { useEffect, useState } from 'react';
import { registerEvent } from '@/pages/center/workflow/utils/HandleUtils';
import styles from '../index.less';
import { request } from '@umijs/max';

export default (props: any) => {
  const [formUrl, setFormUrl] = useState();
  const [loading, setLoading] = useState(false);

  const submit = () => {
    setLoading(true);
    window.frames['form-content'].postMessage({
      cmd: 'submit',
      params: null,
    });
  };

  useEffect(() => {
    registerEvent(
      (params: any) =>
        '/api/workflow/processes/' +
        props.location.query.processDefinitionKey +
        '/start/' +
        params.businessKey,
      'post',
      undefined,
      setLoading,
    );

    const url = '/api/workflow/processes/' +
      props.location.query.processDefinitionKey +
      '/startFormUrl';

    request(url)
      .then((resp: any) => {
        resp = resp.replace('${businessKey}', '');
        resp += resp.indexOf('?') > -1 ? '&' : '?';
        const loginUser = JSON.parse(sessionStorage.getItem('LoginUser')!);
        resp += 'defaultValue=';
        const defaultValue = {
          processStartUser: loginUser.name + '/' + loginUser.username,
        };
        resp += encodeURI(JSON.stringify(defaultValue));
        setFormUrl(resp);
      }).catch(err => {
      message.error('启动工作错误');
      throw err;
    });
  }, []);

  return (
    <div className={styles.content}>
      <h3 className={styles.title}>
        {props.location.query.processDefinitionName}
      </h3>
      <iframe id="form-content" name="form-content" src={formUrl} />
      <div className={styles.submit}>
        <Button type="primary" loading={loading} onClick={submit}>
          提交
        </Button>
      </div>
    </div>
  );
};
